//
//  WBNewFeatureView.swift
//  mySwiftVV
//
//  Created by hu yr on 2017/1/13.
//  Copyright © 2017年 terry. All rights reserved.
//

import UIKit

/// 新特效视图
class WBNewFeatureView: UIView {

    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var enterButton: UIButton!
    @IBOutlet weak var pageControll: UIPageControl!
    
    @IBAction func enterStatus(_ sender: UIButton) {
        
        removeFromSuperview()
    }
    
   
    class func newFeatureView() -> WBNewFeatureView{
        
        let nib  = UINib(nibName: "WBNewFeatureView", bundle: nil)
        
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! WBNewFeatureView
        
        //从 xib 加载的视图默认是 600x600
        v.frame = UIScreen.main.bounds
        
        return v
    }
    
    override func awakeFromNib() {
        //如果使用自动布局设置界面, 从xib 加载默认是 600 * 600 大小
        // 添加 4 个图像视图
        let count = 4
        let rect = UIScreen.main.bounds
        
        for i in 0..<count {
            
            let imageName = "new_feature_\(i + 1)"
            
            let iv = UIImageView(image: UIImage(named: imageName))
            
            //设置大小
            iv.frame = rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0)
            
            scrollView.addSubview(iv)
        }
        
        scrollView.contentSize = CGSize(width: CGFloat(count + 1) * rect.width, height: rect.height)
        
        scrollView.bounces = false
        
        scrollView.isPagingEnabled = true
        
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        
        scrollView.delegate = self
        
        enterButton.isHidden = true
        
    }

}

extension WBNewFeatureView:UIScrollViewDelegate{
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        //1.滚动到最后一屏幕,让视图删除
        
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        //2.判断 是否最后一页
        if page == scrollView.subviews.count {
            
            removeFromSuperview()
        }
        //3.如果是倒数第2页,显示按钮
        enterButton.isHidden = (page != scrollView.subviews.count - 1)
            
        
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        //0.一旦滚动,隐藏按钮
        
        enterButton.isHidden = true
        //1.计算当前的偏移量
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5)
        //2.设置分页控件
        pageControll.currentPage = page
        
        //3.分页控件的隐藏
        pageControll.isHidden = (page == scrollView.subviews.count)
        
        
    }
}
